You walk into the interview room. After a quick greeting, the interviewer smiles — “Alright, let’s start with something classic.”
We’re given the head of a singly linked list. We need to reverse the links between nodes so that the head becomes the tail and the tail becomes the head.
Example:
Input: 1 → 2 → 3 → 4 → 5
Output: 5 → 4 → 3 → 2 → 1
Goal: Change the direction of links, not the node values.
Imagine standing at each node one by one and flipping its arrow (the next pointer) backward.
But to avoid losing track of the next node, we’ll keep three pointers: prev, curr, and nextNode.
function reverseLinkedList(head):
# Initialize previous pointer as null
prev = null
curr = head
# Traverse until the end of the list
while curr is not null:
nextNode = curr.next # Temporarily store next node
curr.next = prev # Reverse the current link
prev = curr # Move prev forward
curr = nextNode # Move curr forward
# After the loop, prev is the new head
return prev
Time Complexity: O(n) — we visit each node once.
Space Complexity: O(1) — only a few variables used.
curr becomes null?prev points to the new head of the reversed list, so we simply return it.function reverseList(head):
# Base case: empty list or single node
if head is null or head.next is null:
return head
# Reverse the rest of the list first
newHead = reverseList(head.next)
# Fix the current node’s link
head.next.next = head
head.next = null
return newHead
Time Complexity: O(n)
Space Complexity: O(n) — recursion stack depth.
Interviewers often test this question not for code, but for how you explain pointer manipulation step by step — that’s where many candidates trip up.
This “simple” question often decides whether you can explain clearly under pressure. Don’t rush to code — narrate your thought process like a story.